package com.example.wanbaqian.base;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.wanbaqian.utils.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * Created by Administrator on 2017/5/8 0008.
 */

public class BaseSQLiteDao {
    private BaseSQLiteOpenHelper openHelper = null;

    public BaseSQLiteDao(Context context) {
        this.openHelper = new BaseSQLiteOpenHelper(context);
    }

    /**
     * 存储一些枚举类型
     *
     * @param json
     * @param type
     * @return
     */
    public BaseSQLiteDao createEnum(String json, final String type) {
        SQLiteDatabase database = openHelper.getWritableDatabase();
        SQLiteDatabase databaseReadable = openHelper.getReadableDatabase();
        try {
            JSONObject jsonObject = new JSONObject(JsonUtils.getInstance().getJsonObject(json, type));
            Iterator<String> sIterator = jsonObject.keys();
            while (sIterator.hasNext()) {
                String key = sIterator.next();
                if (databaseReadable.rawQuery("select * from enum where enum_value=(?) and enum_type=(?)", new String[]{jsonObject.getString(key), type}).getCount() == 0)
                    database.execSQL("insert into enum(enum_key,enum_value,enum_type)values(?,?,?)", new String[]{key, jsonObject.getString(key), type});
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        databaseReadable.close();
        database.close();
        return this;
    }

    /***
     *根据类型去查询
     * @param type
     * @return
     */
    public Cursor selectByType(String type) {
        SQLiteDatabase database = openHelper.getReadableDatabase();
        return database.rawQuery("select * from enum where enum_type=? order by enum_key asc", new String[]{type});
    }
}
